package tv.youxing.android.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import tv.youxing.android.Interface.LoadMoreListener;
import tv.youxing.android.Interface.UpRefUpdateListener;
import tv.youxing.android.R;
import tv.youxing.android.adapter.RecommendAdapter;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.custom.Custom_up_down_refresh_ListView;
import tv.youxing.android.entity.Subscription_Booked;
import tv.youxing.android.ui.LoginActivity;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.ShareUtils;
import tv.youxing.android.utils.StaticClass;

/**
 * Created by apple on 2017/4/19.
 */

/**
 * 项目名：   youxing
 * 包名：     tv.youxing.android .fragment
 * 文件名：   OrderedFragment
 * 创建者：   叶克武
 * 创建时间： 2017/4/19 下午3:04
 * 描述：    TODO
 */
public class OrderedFragment extends BaseFragment {

    @BindView(R.id.lv)
    Custom_up_down_refresh_ListView listView;
    private Subscription_Booked allData;
    private List<Subscription_Booked.ResultBean.DataBean> recommendList = new ArrayList<>();
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.ll_login)
    RelativeLayout ll_login;
    @BindView(R.id.login)
    TextView tvLogin;
    private RecommendAdapter mRecommendAdapter;


    boolean isRef = false;
    int curPageCount = 0;//当前页数

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_recommend, null);
        ButterKnife.bind(this, view);

        initFindView();
        setOnClickListener();


        return view;
    }

    private void initFindView() {
        if (login()) {
            if (ll_login.getVisibility() == View.VISIBLE) {
                ll_login.setVisibility(View.GONE);
            }
            if (mSwipeRefreshLayout.getVisibility() == View.GONE) {
                mSwipeRefreshLayout.setVisibility(View.VISIBLE);
            }


            initListAdapter();
            mSwipeRefreshLayout.setRefreshing(true);
            loadData(null);

        } else {
            //未登录

            if (ll_login.getVisibility() == View.GONE) {
                ll_login.setVisibility(View.VISIBLE);
            }

            if (mSwipeRefreshLayout.getVisibility() == View.VISIBLE) {
                mSwipeRefreshLayout.setVisibility(View.GONE);
            }

            tvLogin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(getContext(), LoginActivity.class));
                }
            });
        }
    }

    int scrollPos=-1;
    int scrollTop=-1;

    private void initListAdapter() {
        mRecommendAdapter = new RecommendAdapter(getActivity(), recommendList);
        listView.setAdapter(mRecommendAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            }
        });
//        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
//                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
//                    scrollPos = listView.getFirstVisiblePosition();
//                    View listV = listView.getChildAt(0);
//
//                    if (listV != null) {
//                        scrollTop = listV.getTop();
//                    } else {
//                        scrollTop = 0;
//                    }
//                }
//            }
//
//            @Override
//            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
//
//            }
//        });

//        listView.setSelectionFromTop(scrollPos,scrollTop);
    }


    boolean login() {
        return ShareUtils.getBoolean(getContext(), AppConst.ISLOGIN, false);
    }


    void loadData(final UpRefUpdateListener listener) {
        curPageCount++;
        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
        params.put("page", curPageCount);


        RxVolley.post(StaticClass.subscriptionBooked, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {


                if (GsonUtils.GsonToBean(t, Subscription_Booked.class).getCode() == 200) {
                    allData = GsonUtils.GsonToBean(t, Subscription_Booked.class);

                    if (allData.getCode() == AppConst.TOKENERROR) {
                        getActivity().startActivity(new Intent(getContext(),LoginActivity.class));
                        return;
                    }

                    recommendList.addAll(allData.getResult().getData());
                    mRecommendAdapter.notifyDataSetChanged();
                    mSwipeRefreshLayout.setRefreshing(false);

                    if (listener != null) {
                        listener.upRef(allData.getResult().getData().size());
                    }
                } else {
                    CustomToast.INSTANCE.showToast("error");
                }
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        initFindView();
    }

    private void initData() {
        mRecommendAdapter.notifyDataSetChanged();
    }


    private void setOnClickListener() {
        /**
         * 下拉刷新
         */
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        recommendList.clear();
                        isRef = false;
                        curPageCount = 0;
                        listView.refreshComplete();
                        loadData(null);
                    }
                }, 1500);
            }
        });

        /**
         * 上拉加载更多
         */
        listView.setLoadMoreListener(new LoadMoreListener() {
            @Override
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {


                        isRef = true;
                        loadData(new UpRefUpdateListener() {
                            @Override
                            public void upRef(int count) {
                                if (count > 0) {
                                    listView.loadMoreComplete();
                                } else {
                                    listView.loadMoreEnd();
                                }
                            }
                        });

//
                    }
                }, 1500);

            }
        });
    }

}
